//
// Created by LiuYou on 2021/10/23.
//

#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <cstring>
#include <csignal>


static int srcFd;
static volatile bool isLoop = false;


static void releaseResources() {
    close( srcFd );

    const char str[] = "释放文件描述符。\n.";
    write( STDOUT_FILENO, str, sizeof( str ) - 1 );
}


void alarmHandler(int signal) {
    isLoop = true;
    alarm( 1 );
}


int main(int argc, char** argv) {
    signal( SIGALRM, alarmHandler );
    alarm( 1 );


    srcFd = open( argv[1], O_RDONLY );
    atexit( releaseResources );


    /*
     * 定时循环。
     */
    char buffer[1024]{};
    ssize_t readBytes{};


    while ((readBytes = read( srcFd, buffer, sizeof( buffer ))) != 0) {
        if (readBytes < 0) {
            perror( "read()" );
            exit( 1 );
        }
        ssize_t writeBytes{};
        int writePos{};
        while ((writeBytes = write( STDOUT_FILENO, buffer + writePos, readBytes )) != readBytes) {
            writePos += static_cast<int>(writeBytes);
            readBytes -= writePos;
        }

        while (!isLoop) {
            pause();
        }
        isLoop = false;

    }


    return 0;
}
